<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽">
    </el-switch>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
  <el-tree :data="menus" :default-expanded-keys="expandedKey" :expand-on-click-node="false" :props="defaultProps"
           ref="tree"
           node-key="catId"
           :draggable="draggable"
           :allow-drop="allowDrop"
           getCheckedNodes
           @node-drop="handleDrop"
           show-checkbox>
    <span slot-scope="{ node, data }" class="custom-tree-node">
        <span @click="editorMenu(data)">{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            size="mini"
            type="text"
            @click="() => append(data)">
            添加
          </el-button>
          <el-button
            v-if="node.childNodes == 0 "
            size="mini"
            type="text"
            @click="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>
  </el-tree>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%">
      <el-form>
        <el-form-item label="活动名称" label-width="120px">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="categoryMenuAddOrEdit">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      draggable: true,
      updateNodesList: [],
      maxLevel: 0,
      editFlag : false,
      menus: [],
      expandedKey: [],
      dialogVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      category: {
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
      },
    }
  },
  components: {},
  created() {
    this.getMenus()
  },
  methods: {
    /**
     * 批量删除方法
     */
    batchDelete(){
      let ids =[]
      //获取选择的ids
      ids = this.$refs.tree.getCheckedKeys()
      console.log(ids)
      this.$http({
        url: this.$http.adornUrl('/product/category/delete'),
        method: 'post',
        data: this.$http.adornData(ids, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getMenus()
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    /**
     * 拖拽成功后
     * @param draggingNode
     * @param dropNode
     * @param dropType
     * @param ev
     */
    handleDrop(draggingNode, dropNode, dropType, ev) {
      //获取当前层级
      let level = dropNode.level
      let pId = 0
      //当前多拽节点的catId
      let catId = draggingNode.data.catId
      // 当前拖拽节点的层级
      if (dropType == 'before' || dropType == 'after'){
         pId = dropNode.parent.data.catId == null ? 0 :dropNode.parent.data.catId
         //获取整个推拽成功后的对象,然后找到存储的位置
       var data =  dropNode.parent.data.children== undefined ? dropNode.parent.data:dropNode.parent.data.children
      this.updateNodes(data,catId,pId,level)
      }else {
        pId = dropNode.data.catId
        var data =  dropNode.data.children
        this.updateNodes(data,catId,pId,level)
      }
      this.$http({
        url: this.$http.adornUrl('/product/category/updateSort'),
        method: 'post',
        data: this.$http.adornData(this.updateNodesList, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: '拖拽成功',
            type: 'success'
          })
        } else {
          this.$message.error(data.msg)
        }
        this.getMenus()
        this.expandedKey = [pId]
        this.updateNodesList=[]
        this.maxLevel = 0
      })
    },
    updateNodes(data,catId,pId,level){
      var sort = -1;
      for (let i = 0; i < data.length; i++) {
        if (data[i].catId == catId){
          sort = i;
          if (level != data[i].catLevel){
            this.updateNodesList.push({catId:catId, parentCid:pId, sort:i, catLevel: level})
            //如果有子层级还要改子层级
            if (data[i].children.length >0){
              for (let j = 0; j < data[i].children.length; j++) {
                this.updateNodesList.push({catId:data[i].children[j].catId, catLevel: level+1})
              }
            }
          }else {
            this.updateNodesList.push({catId:catId, parentCid:pId, sort:i})
          }
        }else {
           this.updateNodesList.push({catId:data[i].catId, sort: i})
        }
      }
    },
    /**
   拖拽功能
     */
    allowDrop(draggingNode, dropNode, type) {
      //被拖动的当前节点以及所在的父节点总层数不能大于3
      this.countNodeLevel(draggingNode.data)
      //当前正在拖动的节点+父节点所在的深度不大于3即可
      let deep = this.maxLevel - draggingNode.data.catLevel + 1;
      if (type == 'inner'){
        return (deep + dropNode.level) <= 3
      }else {
        return (deep + dropNode.parent.level) <=3
      }
    },
    /**
     * 计算被拖拽的层级
     * @param draggingNode
     */
    countNodeLevel(node){
      //找到所有子节点，求出最大深度
      if(node.children != null && node.children.length > 0){
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.maxLevel){
            this.maxLevel = node.children[i].catLevel
          }
         this.countNodeLevel(node.children[i])
        }
      }
    },
      editorMenu(data){
      this.dialogVisible = true
      this.editFlag = true
      this.category = {...data}
    },
    /**
     * 修改/添加三级菜单数据
     */
    categoryMenuAddOrEdit(){
      console.log(this.category)
      //赋值
     if ( !this.editFlag ){
       console.log("添加")
       this.$http({
         url: this.$http.adornUrl('/product/category/save'),
         method: 'post',
         data: this.$http.adornData(this.category, false)
       }).then(({data}) => {
         if (data && data.code === 0) {
           this.$message({
             message: '操作成功',
             type: 'success'
           })
         } else {
           this.$message.error(data.msg)
         }
         this.dialogVisible = false
         this.getMenus()
         this.expandedKey = [this.category.parentCid]
       })
     }else {
       this.$http({
         url: this.$http.adornUrl('/product/category/update'),
         method: 'post',
         data: this.$http.adornData(this.category, false)
       }).then(({data}) => {
         if (data && data.code === 0) {
           this.$message({
             message: '操作成功',
             type: 'success'
           })
         } else {
           this.$message.error(data.msg)
         }
         this.dialogVisible = false
         this.getMenus()
         this.expandedKey = [this.category.parentCid]
       })
     }
    },
    /**
     * 获取菜单
     */
    getMenus() {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({data}) => {
        this.menus = data.data
      })
    },
    append(data) {
      this.editFlag = false
      this.category = {}
      this.dialogVisible = true
      this.category.parentCid = data.catId
      this.category.catLevel = data.catLevel * 1 + 1
      this.category.sort = 0
      this.category.showStatus = 1
      console.log("data->",this.category)
    },
    remove(node, data) {
      let ids = [data.catId]
      this.$confirm(`是否删除[${data.name}]菜单`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.getMenus()
            this.expandedKey = [node.parent.data.catId]
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch(() => {
      })

    }
  }
}
</script>
